package com.iflytek.uoamp.notify.mail.plugins;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.alibaba.fastjson.JSON;
import com.iflytek.uoamp.common.notify.constant.ConstField;
import com.iflytek.uoamp.common.notify.enumerate.ContactState;
import com.iflytek.uoamp.common.notify.enumerate.ContentType;
import com.iflytek.uoamp.common.notify.exception.NotifyException;
import com.iflytek.uoamp.common.notify.format.Formatter;
import com.iflytek.uoamp.common.notify.obj.Contact;
import com.iflytek.uoamp.common.notify.plugins.AbstractPlugin;
import com.iflytek.uoamp.common.notify.plugins.PluginAction;
import com.iflytek.uoamp.common.notify.util.Configurator;
import com.iflytek.uoamp.common.notify.util.LogbackInstance;
import com.iflytek.uoamp.common.notify.util.NotifyUtils;
import com.iflytek.uoamp.notify.mail.format.FixedMailFormatter;
import com.iflytek.uoamp.notify.mail.format.FormatMailFactory;
import com.iflytek.uoamp.notify.mail.format.MailFormatter;

public class MailPlugin extends AbstractPlugin{
	
	private static final String MAIL_FILE = "uoamp-notify/text.mail";
	private static final String MAIL_ACTION = "plugins.mail.action";
	
	private static final Logger logger = LogbackInstance.getInstance().getLogger(MailPlugin.class);
	
	@Override
	public boolean sendContent(String content, List<Contact> contacts) {
	    boolean retVal = false;
	    boolean ignored = true;
	    
		for(Contact contact : contacts) {
            if (StringUtils.isBlank(contact.getEmail())) {
                contact.setState(ContactState.IGNORED);
                String infoLog = MessageFormat.format(ConstField.PASSBYCONTACT, contact.getName(), ConstField.BLANKEMAILADDRESS);
                logInfo.addInfo(infoLog);
                continue;
            }
            ignored = false;
        }
		logger.info("send mail contacts ======================================="+JSON.toJSONString(contacts));
		if(ignored) {
		    logInfo.addError(MessageFormat.format(ConstField.DISABLEPLUGIN, "mail", ConstField.NOPROPERCONTACTS));
		    return false;
		}
        
        try {
        	String path = writeToFile(MAIL_FILE, getJSON(getMailList(contacts),content));
        	logger.info("send mail path ========================="+path);
            String[] params = {"-f", path};
            String pluginPath = Configurator.getInstance().getPropertyByKey(MAIL_ACTION, "");
            logger.info("send mail plugin ==========================="+pluginPath);
            PluginAction.run(pluginPath, params);
            logger.info("send mail succeed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            setState(contacts, ContactState.SUCCESS);
            logInfo.addInfo(MessageFormat.format(ConstField.SENDINGMAIL, getSubject(content), NotifyUtils.getMailList(contacts)));
            retVal = true;
        } catch (NotifyException  e) {
            setState(contacts, ContactState.FAILED);
            logInfo.addError(e.getMessage());
            logger.info("send mail falied because ======="+e.toString());
        }
        
        return retVal;
	}

	@Override
	public Formatter getFormatter() {
	    if(formatter != null) {
	        return formatter;
	    }
	    
		if(useTemplate) {
			ContentType type = ContentType.getType(notification.getContentType());
			String remark = notification.getRemark();
			formatter = FormatMailFactory.getMailFormatter(type);
			((FixedMailFormatter)formatter).setRemark(remark);
		} else {
			formatter = new MailFormatter();
		}
		
		return formatter;
	}
	
	private String getSubject(String content) {
		int pos = content.indexOf("@@");
		
		if(pos != -1) {
			return content.substring(0, pos);
		} else {
			return "";
		}
	}
	
	private List<String> getMailList(List<Contact> contacts) {
	    List<String> mailList = new ArrayList<String>();
	    for(Contact contact : contacts) {
	        if(contact.getState() != ContactState.IGNORED) {
	            mailList.add(contact.getEmail());
	        }
	    }
	    
	    return mailList;
	}
}
